import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // 进度条插件
import 'nprogress/nprogress.css' // 进度条样式
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
// 配置进度条
NProgress.configure({ showSpinner: false }) // NProgress Configuration
// 白名单
const whiteList = ['/login'] // no redirect whitelist
// 前置守卫
router.beforeEach(async(to, from, next) => {
  // 进度条开启
  NProgress.start()

  // 设置标题
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  // 获取token，作为判断是否登陆的依据
  const hasToken = getToken()

  if (hasToken) {
    // 如果登陆了
    if (to.path === '/login') {
      // 登陆了，且去的还是登录页，就跳转到主页去
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      // 登陆了，取得不是登录页
      // 有没有用户的 名称
      const hasGetUserInfo = store.getters.name
      if (hasGetUserInfo) {
        // 有用户名称，放行
        next()
      } else {
        // 没有用户名称，获取一下用户资料
        try {
          // get user info
          await store.dispatch('user/getInfo')

          next()
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // 要去的地址在白名单中，放行
      // in the free login whitelist, go directly
      next()
    } else {
      // 非法登录，去登陆页面
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
